package com.tools;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.Collection;
import java.util.List;

public class SqlLocalTools {

    private static Configuration configuration = new Configuration().configure();
    private static SessionFactory sessionFactory = configuration.buildSessionFactory();
    private static Session session = sessionFactory.openSession();

    public <T> List<T> findBySql(String sql, Object[] params, Class<T> c){
        SQLQuery query = session.createSQLQuery(sql);
        this.setParameters(sql,params,query);
        return null;
    }

    private void setParameters(String sql, Object[] values, Query query){
        this.setParameters(sql,values,query,(String)null);
    }

    private void setParameters(String sql, Object[] values, Query q, String placehoder){
        if (placehoder==null||placehoder.trim().equals("")){
            placehoder = "$";
        }
        Integer i;
        if (sql.indexOf(placehoder)>0){
            if (null != values && values.length > 0) {
                for (i=Integer.valueOf(0);i.intValue()<values.length;i = i.intValue()+1) {
                    Object o = values[i.intValue()];
                    String p = placehoder + i.toString();
                    if (o instanceof Collection) {
                        q.setParameterList(p, (Collection) o);
                    } else if (o.getClass().isArray()) {
                        q.setParameter(p, (Object[]) ((Object[]) ((Object[]) o)));
                    } else {
                        q.setParameter(p, values[i.intValue()]);
                    }

                }
            } else if (null != values && values.length > 0) {
                for (i = Integer.valueOf(0); i.intValue() < values.length; i = i.intValue() + 1) {
                    q.setParameter(i.intValue(), values[i.intValue()]);
                }
            }
        }
    }

}
